package player

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/errors"
	"GameServer/Game/lib"
	"GameServer/Game/sp"
	"fmt"
)

// 成就信息 8200
func (p *Player) AchievementInfoRequest(req *sp.AchievementInfoRequest) (res *sp.AchievementInfoResponse, err error) {
	u := p.User
	// 获取成就信息
	res = &sp.AchievementInfoResponse{
		Lst:      lib.FormatAchievInfoSps(u),
		AchTotal: lib.FormatAchievTotalSp(u),
	}

	return
}

// 领取成就 8201
func (p *Player) AchievementRewardRequest(req *sp.AchievementRewardRequest) (res *sp.AchievementRewardResponse, err error) {
	u := p.User
	// 领取成就星星
	uProp, err := lib.GetAchievProgress("AchievementRewardRequest", u, req.Tid, req.Type, p.Send)
	if err != nil {
		fmt.Println("领取星星失败")
		res = &sp.AchievementRewardResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	// 成就，记录获取星星数量。
	lib.AddAchievProgress(u, data.AchievementType.Get_stars, u.StarVal())
	p.TimelyUpdateProp(req.GetType(), uProp)
	utils.AsyncFunc(func() {
		p.UpdateProp(req.GetType(), uProp)
	})
	// 计算新兵特训
	lib.RecruitTrainMsg(u.Uid.Hex(), 0, u.StarSum, 0, p.Send)

	// 自动领取累计道具
	resList, err := lib.AchievTotalRecvReward(u)
	if err != nil {
		fmt.Println("获取累计道具失败")
		res = &sp.AchievementRewardResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}

	uProp1, resGoods, boxResList, err := lib.GiveGoodsByKvList("AchievementRewardRequest", u, resList, p.Send)
	if err != nil {
		fmt.Println("自动领取累计道具失败")
		res = &sp.AchievementRewardResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	// 有成就完成，进行通知
	achLst := lib.AchievComplete(p.User)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}

	res = &sp.AchievementRewardResponse{
		Lst:      lib.FormatAchievInfoSp(u, req.Tid, req.Type),
		AchTotal: lib.FormatAchievTotalSp(u),
		Res:      lib.FormatGoodsInfoSps(resGoods),
		BoxRes:   lib.FormatBoxResSps(boxResList),
	}

	p.TimelyUpdateProp(req.GetType(), uProp1)
	utils.AsyncFunc(func() {
		p.UpdateProp(req.GetType(), uProp1)
	})
	return
}

// 有成就完成，进行通知
func (p *Player) AchievementNotice() {
	achLst := lib.AchievComplete(p.User)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}
}
